package org.example.tool;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HuffmanTreeOutputStream {
    private DataOutputStream outputStream;
    public HuffmanTreeOutputStream(OutputStream outputStream) {
        this.outputStream = new DataOutputStream(outputStream);
    }
    private void writeNode(HuffmanTree.Node node) throws IOException {
        if(node == null) {
            this.outputStream.writeChar(0);
            return;
        }
        if(!node.isLeaf()){
            this.outputStream.writeChar(1);
            writeNode(node.zero);
            writeNode(node.one);
        }
        else {
            if(node.getChar() == 0 || node.getChar() == 1 || node.getChar() == '\\') {
                this.outputStream.writeChar('\\');
            }
            this.outputStream.writeChar(node.getChar());
        }
    }
    public void writeTree(HuffmanTree huffmanTree) throws IOException {
        HuffmanTree.Node root = huffmanTree.getRoot();
        writeNode(root);
    }

    public void close() throws IOException {
        this.outputStream.close();
    }

    public void flush() throws IOException {
        this.outputStream.flush();
    }

}
